package com.nny.alarm.audio;

import java.io.IOException;

import com.nny.alarm.R;
import com.uxwine.util.Log;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

public class RingManager {
	
	private int[] mRings;
	private Context mCtx;
	private static RingManager mInstance;
	public SharedPreferences mSpf;
	private MediaPlayer mPlayer;
	private float mfVolume;
	
	private static final String TAG = RingManager.class.getName();	
	private static final String SPF_NAME = "spf.ring";
	private static final String SPF_KEY_VOLUME = "spf.ring.volume";
	
	public RingManager(Context ctx)
	{
		mCtx = ctx.getApplicationContext();
		mSpf = mCtx.getSharedPreferences(SPF_NAME, 0);
		mRings = new int[]{R.raw.ring_0, 
				R.raw.ring_0, 
				R.raw.ring_0, 
				R.raw.ring_0, 
				R.raw.ring_0, 
				R.raw.ring_0, 
				R.raw.ring_0, 
				R.raw.ring_0};
		mfVolume = mSpf.getFloat(SPF_KEY_VOLUME, 1.0f);
	}
	
	public void play(int id)
	{
		if(id < 0 || id > 7)
			return;
		
		startPlayer(id);
	}
	
	private synchronized boolean startPlayer(int id)
	{
		stop();
		
		mPlayer = MediaPlayer.create(mCtx, mRings[id]);
		//mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
		mPlayer.setVolume(mfVolume, mfVolume);
		mPlayer.setLooping(true);
		mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				cleanupPlayer(mp);
			}
		});
		mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
			public boolean onError(MediaPlayer mp, int what, int extra) {
				cleanupPlayer(mp);
				return true;
			}
		});
		try 
		{
			//mPlayer.prepare();
			mPlayer.start();
		} 
		catch (Exception e) {Log.e(e);} 
			
		return false;
	}
	
	private synchronized void cleanupPlayer(MediaPlayer mp)
	{
		mp.release();
		mPlayer = null;
	}
	
	public void stop()
	{
		if(mPlayer != null)
		{
			//if(mPlayer.isPlaying())
				//mPlayer.stop();
			mPlayer.release();
		}
	}
}
